const axios = require('axios')
const moment =require('moment')
const {corpId, corpSecret, classesMo, agentId, classesSheng} = require("../config/class.config");
const {tips} = require("../common/class.tips");

//获取企业微信推送的token
const getToken = async (corpsecret) => {
    let url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpId}&corpsecret=${corpsecret}`
    let res = await axios.get(url)
    let token = res.data.access_token
    return token;
}
//获取并包装课表
const getClass=(agentid)=>{
    //开学时间 和 现在时间
    let beginTime = moment('2022-08-22')
    let nowTime = moment();
    //现在是第几周
    let nowWeek=nowTime.diff(beginTime,'weeks')+1
    let [...classes]=(agentid===1000004)?classesMo:classesSheng;
    //判断周
    for (let i = 0; i < 7; i++) {
        for (let j = 0; j < 5; j++) {
            let theClass = classes[i][j]
            let classTime = theClass.time
            if (classTime !== undefined) {
                let classTimes = classTime.split('-');
                if (nowWeek < classTimes[0] || nowWeek > classTimes[1]) {
                    classes[i][j] = ''
                }
            }
        }
    }
    //判断今天周几
    let week = moment().weekday();
    week = (week === 6) ? 0 : week + 1;
    let todayClass = classes[week]
    //提取明天的的
    let count = 0
    let flag = [];
    for (let i = 0; i < 5; i++) {
        if (todayClass[i] !== '') {
            count++;
            flag.push(i)
        }
    }
    let des = []
    let times = ['8:00-10:00', '10:10-12:00', '2:00-4:00', '4:00-6:00', '7:00-10:00']
    let tmp=['1-2','3-4','5-6','7-8','9-10']
    for (const flagElement of flag) {
        let msg = `${tmp[flagElement]}节  ${times[flagElement]}\n${todayClass[flagElement].name}@${todayClass[flagElement].pos}\n`
        des.push(msg)
    }
    des = des.join('\n')
    let index = Math.floor(Math.random() * tips.length)
    return `你明天有 ${count} 节课\n\n${des}\n${tips[index]}`;
}
//发送课表
const send_msg = async (token,agentid) => {
    let description =getClass(agentid)
    let data = {
        "touser": "@all",
        "agentid": agentid,
        "msgtype": "textcard",
        "textcard": {
            "title": "专属课表提醒",
            "description": description,
            "url": "URL",
            "btntxt": "更多"
        },
    }
    let url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${token}&debug=1`
    let res = await axios.post(url, data)
    return res.data
}
//自执行主函数
(async function () {
    console.log('进入课表推送')
    let corpsecret = corpSecret;
    let agentid = agentId;
    for (let i = 0; i < 2; i++) {
        let token = await getToken(corpsecret[i])
        let res = await send_msg(token, agentid[i])
        console.log(res)
        if (res.errcode === 0) {
            if (i === 0) {
                console.log('墨墨课表推送成功')
            } else {
                console.log('蒜蒜课表推送成功')
            }
        }
    }
})()
